﻿using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace QwenAIApp
{
    internal class Program
    {
        private static readonly HttpClient httpClient = new HttpClient();

        static async Task Main(string[] args)
        {
            // 若没有配置环境变量，请用百炼API Key将下行替换为：string? apiKey = "sk-xxx";
            string? apiKey = Environment.GetEnvironmentVariable(
                "QwenApiKey",
                EnvironmentVariableTarget.Machine
            );

            if (string.IsNullOrEmpty(apiKey))
            {
                Console.WriteLine("API Key 未设置。请确保环境变量 'DASHSCOPE_API_KEY' 已设置。");
                return;
            }
            // 设置请求头
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                "Bearer",
                apiKey
            );
            httpClient.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json")
            );
            // 设置请求 URL 和内容
            string url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
            // 模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
            string jsonContent =
                @"{
            ""model"": ""qwen2-vl-7b-instruct"",
            ""stream"": true,
            ""stream_options"":{
                 ""include_usage"": true
            },   
            ""messages"":messagesContent
        }";
            List<ChatMessage> messages = new List<ChatMessage>();
            messages.Add(new ChatMessage() { role = "system", content = "你是一个C#高手" });

            while (true)
            {
                Console.Write("User:");
                var usermessage = Console.ReadLine();
                if (string.IsNullOrEmpty(usermessage))
                {
                    continue;
                }
                if (usermessage == "exit")
                {
                    break;
                }
                var user = new ChatMessage() { role = "user", content = usermessage };
                messages.Add(user);
                var str = JsonSerializer.Serialize(messages);
                var send = jsonContent.Replace("messagesContent", str);
                // 发送请求并获取响应
                Console.WriteLine("assistant:");

                var result = await SendPostRequestAsync(url, send, apiKey);
                messages.Add(new ChatMessage() { role = "assistant", content = result });
            }

            // 输出结果
            // Console.WriteLine(result);
        }

        private static async Task<string> SendPostRequestAsync(
            string url,
            string jsonContent,
            string apiKey
        )
        {
            using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
            {
                // 发送请求并获取响应
                HttpResponseMessage response = await httpClient.PostAsync(url, content);

                // 处理响应
                if (response.IsSuccessStatusCode)
                {
                    string result = "";
                    using (Stream stream = await response.Content.ReadAsStreamAsync())
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        string line;
                        while ((line = await reader.ReadLineAsync()) != null)
                        {
                            if (string.IsNullOrEmpty(line))
                                continue;
                            string data = line.Substring(6);
                            if (data == "[DONE]")
                            {
                                //结束标志
                                break;
                            }
                            var streamObject = JsonSerializer.Deserialize<StreamObject>(data);
                            if (streamObject.choices.Count() > 0)
                            {
                                var contentRes = streamObject.choices[0].delta.content;
                                Console.Write(contentRes);
                                result += contentRes;
                            }
                            if (streamObject.usage != null)
                            {
                                Console.WriteLine(
                                    $"Usage: prompt_tokens:{streamObject.usage.prompt_tokens}, completion_tokens:{streamObject.usage.completion_tokens}, total_tokens:{streamObject.usage.total_tokens}"
                                );
                            }
                            Thread.Sleep(200);
                        }
                        Console.WriteLine();
                    }
                    return result;
                    // return await response.Content.ReadAsStringAsync();
                }
                else
                {
                    Console.WriteLine($"请求失败: {response.StatusCode}");
                    return $"请求失败: {response.StatusCode}";
                }
            }
        }
    }
}
